import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/index/even/clear_index_company_info_event.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';

class CompanySwitchViewModel extends BaseViewModel {

  ValueNotifier<List<OrgInfoListBean>> valueNotifier;

  ///App切换企业
  static const String _APP_CHANGE_COMPANY_API =
     ServerApi.BASE_URL + "app/appChangeCompany";

  ///获取该账号所属机构
  static const String SEARCH_ORGANIZATION_API =
     ServerApi.BASE_URL + "/app/searchOrganization";

  CompanySwitchViewModel(BaseState<StatefulWidget> state) : super(state){
    valueNotifier = ValueNotifier(null);
  }

  ///切换公司请求
  void changeCompanyHttp(BuildContext context, String newCompanyId,bool loginPage) {
    if (newCompanyId == null || newCompanyId == "") {
      VgToastUtils.toast(context, "切换公司未获取成功");
      VgEventBus.global.send(new ClearIndexCompanyInfoEvent(true));
      return;
    }
    if (newCompanyId == UserRepository.getInstance().companyId) {
      if(!(loginPage??false)){
        RouterUtils.pop(context,result: true);
        return;
      }
      // VgToastUtils.toast(context, "请选择切换对象");
    }
    VgHudUtils.show(context, "正在切换");
    VgHttpUtils.get(_APP_CHANGE_COMPANY_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "changeCompanyId": newCompanyId ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          ///清空首页缓存数据
          String terCacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
          String homeCacheKey = UserRepository.getInstance().getHomeCompanyBaseInfoCacheKey();
          ///获取缓存数据
          SharePreferenceUtil.putString(terCacheKey, "");
          SharePreferenceUtil.putString(homeCacheKey, "");
          _autoLogin(context);
        }, onError: (msg) {
          VgEventBus.global.send(new ClearIndexCompanyInfoEvent(true));
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  ///切换成功，进行自动登录
  void _autoLogin(BuildContext context) {
    UserRepository.getInstance()
        .loginService(
            isBackIndexPage: false,
            callback: VgBaseCallback(onSuccess: (UserDataBean userDataBean) {
              VgHudUtils.hide(context);
              RouterUtils.pop(context,result: true);
              // VgToastUtils.toast(AppMain.context, "切换成功");
            }, onError: (String msg) {
              VgHudUtils.hide(context);
              VgToastUtils.toast(context, msg);
              VgEventBus.global.send(new ClearIndexCompanyInfoEvent(true));
            }))
        .autoLogin();
  }

  ///获取该账号一起学机构
  void searchOrganization(
      BuildContext context, String phone) {
    if (phone == null || phone == "") {
      return;
    }
    if(phone.length != DEFAULT_PHONE_LENGTH_LIMIT){
      return;
    }
    VgHttpUtils.get(SEARCH_ORGANIZATION_API,
        params: {
          "phone": globalSubPhone(phone) ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          LoginSearchOrganizationBean bean = LoginSearchOrganizationBean.fromMap(val);
          if((bean?.data?.orgInfoList?.length??0)!=0){
            valueNotifier?.value = val = bean?.data?.orgInfoList;
          }
        }, onError: (msg) {

        }));
  }
}
